package com.dao.impl;

import com.dao.StudentsDao;
import com.entity.Students;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Repository //真正的 学生服务层的实现类
//@Service
public class StudentsDaoImpl implements StudentsDao {


    @Resource
    private JdbcTemplate jdbcTemplate;

    @Override
    public boolean add(Students s) throws Exception {
        System.out.println("***********执行新增学生********");
        String sql = "INSERT INTO students VALUES(?, ?, ?, ?)";
        int result = jdbcTemplate.update(sql, s.getSid(), s.getSname(), s.getGender(),s.getMajor());
        if(result>0){
            return true;
        }
        return false;
    }

    @Override
    public Students queryById(String id) {
        System.out.println("***********查询编号为："+id+"的学生********");
        String sql = "SELECT * FROM students WHERE sid = ?";
        RowMapper<Students> rowMapper =new BeanPropertyRowMapper<>(Students.class);
        // 在将数据装入对象时需要调用set方法。
        Students s = jdbcTemplate.queryForObject(sql, rowMapper, id);
        return s;
    }

    @Override
    public List<Students> queryAll() {
        System.out.println("***********查询所有学生********");
        String sql = "SELECT * from students";
        RowMapper<Students> rowMapper = new BeanPropertyRowMapper<>(Students.class);
        List<Students> studentsList = jdbcTemplate.query(sql, rowMapper);
        return studentsList;
    }

    @Override
    public boolean update(Students s) throws Exception {
        System.out.println("***********更新学生********");
        String sql = "UPDATE students SET sname = ?, gender=?,major=? WHERE sid = ?";
        jdbcTemplate.update(sql, s.getSname(),s.getGender(),s.getMajor(), s.getSid());
        return true;
    }

    @Override
    public boolean delete(String id) throws Exception {
        System.out.println("***********删除编号为："+id+"的学生********");
        String sql = "DELETE from students WHERE sid = ?";
        jdbcTemplate.update(sql, id);
        return true;
    }

    @Override
    public void addBatch(List<Students> objs) throws Exception {
        String sql = "INSERT INTO students VALUES(?, ?, ?, ?)";
        List<Object[]> batchArgs = new ArrayList<>();
        for(Students s: objs){
            batchArgs.add(new Object[] { s.getSid(), s.getSname(), s.getGender(),s.getMajor() });
        }

        jdbcTemplate.batchUpdate(sql, batchArgs);
    }
}
